package com.xy.xyaicpzs.dlt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xy.xyaicpzs.domain.entity.*;
import com.xy.xyaicpzs.mapper.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 后区首球预测器
 */
@Slf4j
@Component
public class BackBallPredictor {

    @Autowired
    private D6Mapper d6Mapper;

    @Autowired
    private D10Mapper d10Mapper;

    @Autowired
    private D11Mapper d11Mapper;

    @Autowired
    private DltBackendHistoryTop100Mapper dltBackendHistoryTop100Mapper;

    @Autowired
    private DltBackendHistoryTopMapper dltBackendHistoryTopMapper;

    /**
     * 球号和系数的关联类
     */
    @Data
    public static class BallWithCoefficient {
        private Integer ballNumber;
        private Double coefficient;
        private Integer masterBallNumber; // 主球号，用于标识来源

        public BallWithCoefficient(Integer ballNumber, Double coefficient, Integer masterBallNumber) {
            this.ballNumber = ballNumber;
            this.coefficient = coefficient;
            this.masterBallNumber = masterBallNumber;
        }

        @Override
        public String toString() {
            return "Ball{" +
                    "ballNumber=" + ballNumber +
                    ", coefficient=" + coefficient +
                    ", masterBallNumber=" + masterBallNumber +
                    '}';
        }
    }

    /**
     * 后区首球预测结果类
     */
    @Data
    public static class BackBallPredictionResult {
        private List<Integer> result;
        private String filteringProcess;
        
        public BackBallPredictionResult(List<Integer> result, String filteringProcess) {
            this.result = result;
            this.filteringProcess = filteringProcess;
        }
    }
    
    /**
     * 后区首球预测（带过程）
     * @param level 位置级别（high/middle/low）
     * @param nextFrontBalls 下期前区5个号码
     * @param previousFrontBalls 上期前区5个号码
     * @param previousBackBalls 上期后区2个号码
     * @param nextBackBalls 下期后区2个号码
     * @return 预测的4个后区首球号码和筛选过程
     */
    public BackBallPredictionResult predictBackBallWithProcess(String level, List<Integer> nextFrontBalls, List<Integer> previousFrontBalls, 
                                     List<Integer> previousBackBalls, List<Integer> nextBackBalls) {
        // 参数验证
        validateInputParams(level, nextFrontBalls, previousFrontBalls, previousBackBalls, nextBackBalls);
        
        // 存放D6表中对应的系数，用于后续筛选
        Map<Integer, List<BallWithCoefficient>> d6CoefficientMap = new HashMap<>();
        
        // 所有候选球列表
        List<Integer> allCandidateBalls = new ArrayList<>();
        
        // 步骤一：处理下期前区5个号码
        for (Integer nextFrontBall : nextFrontBalls) {
            List<BallWithCoefficient> ballsWithCoefficients;
            
            if ("high".equalsIgnoreCase(level)) {
                ballsWithCoefficients = getHighLevelBallsFromD6(nextFrontBall);
            } else if ("middle".equalsIgnoreCase(level)) {
                ballsWithCoefficients = getMiddleLevelBallsFromD6(nextFrontBall);
            } else { // low
                ballsWithCoefficients = getLowLevelBallsFromD6(nextFrontBall);
            }
            
            for (BallWithCoefficient ball : ballsWithCoefficients) {
                d6CoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤二：处理上期前区5个号码
        for (Integer previousFrontBall : previousFrontBalls) {
            List<BallWithCoefficient> ballsFromD10 = getTop10BallsFromD10(previousFrontBall);
            for (BallWithCoefficient ball : ballsFromD10) {
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤三：处理上期后区2个号码
        for (Integer previousBackBall : previousBackBalls) {
            List<BallWithCoefficient> ballsFromD11 = getTop10BallsFromD11(previousBackBall);
            for (BallWithCoefficient ball : ballsFromD11) {
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤四：从历史排行表获取前2名
        List<Integer> top2FromHistoryTop = getTop2FromBackendHistoryTop();
        allCandidateBalls.addAll(top2FromHistoryTop);
        
        // 步骤五：从百期排行表获取前2名
        List<Integer> top2FromHistoryTop100 = getTop2FromBackendHistoryTop100();
        allCandidateBalls.addAll(top2FromHistoryTop100);

        return selectFinal4BallsWithProcess(allCandidateBalls, d6CoefficientMap);
    }
    
    /**
     * 后区首球预测主方法
     * @param level 位置级别（high/middle/low）
     * @param nextFrontBalls 下期前区5个号码
     * @param previousFrontBalls 上期前区5个号码
     * @param previousBackBalls 上期后区2个号码
     * @param nextBackBalls 下期后区2个号码
     * @return 预测的4个后区首球号码
     */
    public List<Integer> predictBackBall(String level, List<Integer> nextFrontBalls, List<Integer> previousFrontBalls, 
                                     List<Integer> previousBackBalls, List<Integer> nextBackBalls) {
        // 参数验证
        validateInputParams(level, nextFrontBalls, previousFrontBalls, previousBackBalls, nextBackBalls);
        
        // 存放D6表中对应的系数，用于后续筛选
        Map<Integer, List<BallWithCoefficient>> d6CoefficientMap = new HashMap<>();
        
        // 所有候选球列表
        List<Integer> allCandidateBalls = new ArrayList<>();
        
        // 步骤一：处理下期前区5个号码
        for (Integer nextFrontBall : nextFrontBalls) {
            List<BallWithCoefficient> ballsWithCoefficients;
            
            if ("high".equalsIgnoreCase(level)) {
                ballsWithCoefficients = getHighLevelBallsFromD6(nextFrontBall);
            } else if ("middle".equalsIgnoreCase(level)) {
                ballsWithCoefficients = getMiddleLevelBallsFromD6(nextFrontBall);
            } else { // low
                ballsWithCoefficients = getLowLevelBallsFromD6(nextFrontBall);
            }
            
            for (BallWithCoefficient ball : ballsWithCoefficients) {
                d6CoefficientMap.computeIfAbsent(ball.getBallNumber(), k -> new ArrayList<>()).add(ball);
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤二：处理上期前区5个号码
        for (Integer prevFrontBall : previousFrontBalls) {
            List<BallWithCoefficient> prevFrontBallCandidates = getTop10BallsFromD10(prevFrontBall);
            for (BallWithCoefficient ball : prevFrontBallCandidates) {
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤三：从历史排行表获取最大值向下的2个球
        List<Integer> top2HistoryTop = getTop2FromBackendHistoryTop();
        allCandidateBalls.addAll(top2HistoryTop);
        
        // 步骤四：从百期排行表获取最大值向下的2个球
        List<Integer> top2HistoryTop100 = getTop2FromBackendHistoryTop100();
        allCandidateBalls.addAll(top2HistoryTop100);
        
        // 步骤五：处理上期后区2个号码
        for (Integer prevBackBall : previousBackBalls) {
            List<BallWithCoefficient> prevBackBallCandidates = getTop10BallsFromD11(prevBackBall);
            for (BallWithCoefficient ball : prevBackBallCandidates) {
                allCandidateBalls.add(ball.getBallNumber());
            }
        }
        
        // 步骤六：加入下期后区2个号码
        for (Integer nextBackBall : nextBackBalls) {
            allCandidateBalls.add(nextBackBall);
        }
        
        // 最终筛选4个球
        return selectFinal4Balls(allCandidateBalls, d6CoefficientMap);
    }
    
    /**
     * 高位策略：从D6表中获取最大值向下的5个球号
     */
    private List<BallWithCoefficient> getHighLevelBallsFromD6(Integer masterBallNumber) {
        List<D6> d6List = d6Mapper.selectList(
            new LambdaQueryWrapper<D6>()
                .eq(D6::getMasterBallNumber, masterBallNumber));
        if (CollectionUtils.isEmpty(d6List)) {
            log.warn("No D6 records found for master ball: {}", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 按系数从大到小排序
        d6List.sort((d1, d2) -> d2.getCoefficient().compareTo(d1.getCoefficient()));
        
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 5 && index < d6List.size()) {
            double currentCoefficient = d6List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < d6List.size() && 
                   d6List.get(index).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d6List.get(index).getSlaveBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(5 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 中位策略：从D6表中获取平均值及其附近的5个球号
     */
    private List<BallWithCoefficient> getMiddleLevelBallsFromD6(Integer masterBallNumber) {
        List<D6> d6List = d6Mapper.selectList(
            new LambdaQueryWrapper<D6>()
                .eq(D6::getMasterBallNumber, masterBallNumber));
        if (CollectionUtils.isEmpty(d6List)) {
            log.warn("No D6 records found for master ball: {}", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 按系数从大到小排序
        d6List.sort((d1, d2) -> d2.getCoefficient().compareTo(d1.getCoefficient()));
        
        // 计算平均系数
        double avgCoefficient = d6List.stream()
                .mapToDouble(D6::getCoefficient)
                .average()
                .orElse(0.0);
        
        // 找到比平均值大且最接近平均值的位置（从下到上遍历）
        int avgPosition = -1;
        for (int i = d6List.size() - 1; i >= 0; i--) {
            double diff = d6List.get(i).getCoefficient() - avgCoefficient;
            if (diff >= 0) {
                avgPosition = i;
                break; // 找到第一个比平均值大的位置就停止
            }
        }
        
        // 如果没找到大于平均值的系数，取第一个
        if (avgPosition == -1) {
            avgPosition = 0;
        }
        
        List<BallWithCoefficient> result = new ArrayList<>();
        
        // 先加入平均值位置的球号
        result.add(new BallWithCoefficient(d6List.get(avgPosition).getSlaveBallNumber(), 
                d6List.get(avgPosition).getCoefficient(), masterBallNumber));
        
        // 向上取2个球号（使用高位策略的毛边处理逻辑）
        List<BallWithCoefficient> upperBalls = getUpperBallsFromAverageD6(d6List, avgPosition, 2, masterBallNumber);
        result.addAll(upperBalls);
        
        // 向下取2个球号（使用低位策略的毛边处理逻辑）
        List<BallWithCoefficient> lowerBalls = getLowerBallsFromAverageD6(d6List, avgPosition, 2, masterBallNumber);
        result.addAll(lowerBalls);
        
        return result;
    }
    
    /**
     * 从D6表平均值位置向上取指定数量的球号
     */
    private List<BallWithCoefficient> getUpperBallsFromAverageD6(List<D6> d6List, int avgPosition, int needCount, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = avgPosition - 1; // 从平均值位置的上一个开始
        int addedCount = 0;
        
        // 从平均值向上遍历（使用高位策略的逻辑）
        while (addedCount < needCount && index >= 0) {
            double currentCoefficient = d6List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号（向前收集）
            int tempIndex = index;
            while (tempIndex >= 0 && 
                   d6List.get(tempIndex).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d6List.get(tempIndex).getSlaveBallNumber());
                tempIndex--;
            }
            
            // 更新index为下一个不同系数的位置
            index = tempIndex;
            
            // 计算还需要多少个球
            int needFromGroup = Math.min(needCount - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needFromGroup == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边（向上使用高位策略）
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needFromGroup);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 从D6表平均值位置向下取指定数量的球号
     */
    private List<BallWithCoefficient> getLowerBallsFromAverageD6(List<D6> d6List, int avgPosition, int needCount, Integer masterBallNumber) {
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = avgPosition + 1; // 从平均值位置的下一个开始
        int addedCount = 0;
        
        // 从平均值向下遍历（使用低位策略的逻辑）
        while (addedCount < needCount && index < d6List.size()) {
            double currentCoefficient = d6List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号（向后收集）
            int tempIndex = index;
            while (tempIndex < d6List.size() && 
                   d6List.get(tempIndex).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d6List.get(tempIndex).getSlaveBallNumber());
                tempIndex++;
            }
            
            // 更新index为下一个不同系数的位置
            index = tempIndex;
            
            // 计算还需要多少个球
            int needFromGroup = Math.min(needCount - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needFromGroup == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边（向下使用后区策略）
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needFromGroup);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 低位策略：从D6表中获取最小值向上5个球号
     */
    private List<BallWithCoefficient> getLowLevelBallsFromD6(Integer masterBallNumber) {
        List<D6> d6List = d6Mapper.selectList(
            new LambdaQueryWrapper<D6>()
                .eq(D6::getMasterBallNumber, masterBallNumber));
        if (CollectionUtils.isEmpty(d6List)) {
            log.warn("No D6 records found for master ball: {}", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 按系数从大到小排序
        d6List.sort((d1, d2) -> d2.getCoefficient().compareTo(d1.getCoefficient()));
        
        // 找到最小值的位置
        int minPosition = d6List.size() - 1;
        
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = minPosition;
        int addedCount = 0;
        
        // 从最小值开始向上遍历
        while (addedCount < 5 && index >= 0) {
            double currentCoefficient = d6List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号（向前收集）
            int tempIndex = index;
            while (tempIndex >= 0 && 
                   d6List.get(tempIndex).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d6List.get(tempIndex).getSlaveBallNumber());
                tempIndex--;
            }
            
            // 更新index为下一个不同系数的位置
            index = tempIndex;
            
            // 计算还需要多少个球
            int needCount = Math.min(5 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 从D10表中获取最大值向下的10个球号
     */
    private List<BallWithCoefficient> getTop10BallsFromD10(Integer masterBallNumber) {
        List<D10> d10List = d10Mapper.selectList(
            new LambdaQueryWrapper<D10>()
                .eq(D10::getMasterBallNumber, masterBallNumber));
        if (CollectionUtils.isEmpty(d10List)) {
            log.warn("No D10 records found for master ball: {}", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 按系数从大到小排序
        d10List.sort((d1, d2) -> d2.getCoefficient().compareTo(d1.getCoefficient()));
        
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 10 && index < d10List.size()) {
            double currentCoefficient = d10List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < d10List.size() && 
                   d10List.get(index).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d10List.get(index).getSlaveBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(10 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }
    
    /**
     * 从D11表中获取最大值向下的10个球号
     */
    private List<BallWithCoefficient> getTop10BallsFromD11(Integer masterBallNumber) {
        List<D11> d11List = d11Mapper.selectList(
            new LambdaQueryWrapper<D11>()
                .eq(D11::getMasterBallNumber, masterBallNumber));
        if (CollectionUtils.isEmpty(d11List)) {
            log.warn("No D11 records found for master ball: {}", masterBallNumber);
            return new ArrayList<>();
        }
        
        // 按系数从大到小排序
        d11List.sort((d1, d2) -> d2.getCoefficient().compareTo(d1.getCoefficient()));
        
        List<BallWithCoefficient> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 10 && index < d11List.size()) {
            double currentCoefficient = d11List.get(index).getCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < d11List.size() && 
                   d11List.get(index).getCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(d11List.get(index).getSlaveBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(10 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(new BallWithCoefficient(sameCoefficientBalls.get(0), currentCoefficient, masterBallNumber));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                for (int i = 0; i < sameCoefficientBalls.size(); i++) {
                    result.add(new BallWithCoefficient(sameCoefficientBalls.get(i), currentCoefficient, masterBallNumber));
                }
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                for (Integer selectedBall : selectedBalls) {
                    result.add(new BallWithCoefficient(selectedBall, currentCoefficient, masterBallNumber));
                    addedCount++;
                }
            }
        }
        
        return result;
    }

    /**
     * 获取后区历史排行表中最大值向下的2位
     */
    private List<Integer> getTop2FromBackendHistoryTop() {
        List<DltBackendHistoryTop> historyTopList = dltBackendHistoryTopMapper.selectList(
            new LambdaQueryWrapper<DltBackendHistoryTop>()
                .orderByDesc(DltBackendHistoryTop::getActiveCoefficient));
        if (CollectionUtils.isEmpty(historyTopList)) {
            return new ArrayList<>();
        }
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 2 && index < historyTopList.size()) {
            double currentCoefficient = historyTopList.get(index).getActiveCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < historyTopList.size() && 
                   historyTopList.get(index).getActiveCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(historyTopList.get(index).getBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(2 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(sameCoefficientBalls.get(0));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                result.addAll(sameCoefficientBalls);
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }

    /**
     * 获取后区百期排行表中最大值向下的2位
     */
    private List<Integer> getTop2FromBackendHistoryTop100() {
        List<DltBackendHistoryTop100> historyTop100List = dltBackendHistoryTop100Mapper.selectList(
            new LambdaQueryWrapper<DltBackendHistoryTop100>()
                .orderByDesc(DltBackendHistoryTop100::getActiveCoefficient));
        if (CollectionUtils.isEmpty(historyTop100List)) {
            return new ArrayList<>();
        }
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < 2 && index < historyTop100List.size()) {
            double currentCoefficient = historyTop100List.get(index).getActiveCoefficient();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < historyTop100List.size() && 
                   historyTop100List.get(index).getActiveCoefficient().equals(currentCoefficient)) {
                sameCoefficientBalls.add(historyTop100List.get(index).getBallNumber());
                index++;
            }
            
            // 计算还需要多少个球
            int needCount = Math.min(2 - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(sameCoefficientBalls.get(0));
                addedCount++;
            } else if (needCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                result.addAll(sameCoefficientBalls);
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，处理毛边
                List<Integer> selectedBalls = handleMultipleBoundaryConflicts(sameCoefficientBalls, needCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }
    
    /**
     * 处理多个边界冲突，选择指定数量的球号
     * @param candidateBalls 候选球号列表
     * @param selectCount 需要选择的数量
     * @return 选中的球号列表
     */
    private List<Integer> handleMultipleBoundaryConflicts(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 1. 先从dlt_backend_history_top_100比较
        Map<Integer, Double> top100Coefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            DltBackendHistoryTop100 record = dltBackendHistoryTop100Mapper.selectOne(
                new LambdaQueryWrapper<DltBackendHistoryTop100>()
                    .eq(DltBackendHistoryTop100::getBallNumber, ball));
            if (record != null) {
                top100Coefficients.put(ball, record.getActiveCoefficient());
            } else {
                top100Coefficients.put(ball, 0.0);
            }
        }
        
        // 按系数降序排序
        List<Map.Entry<Integer, Double>> sortedByTop100 = top100Coefficients.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        
        // 按系数分组处理
        int currentIndex = 0;
        while (result.size() < selectCount && currentIndex < sortedByTop100.size()) {
            Double currentCoefficient = sortedByTop100.get(currentIndex).getValue();
            List<Integer> sameTop100CoefficientBalls = new ArrayList<>();
            
            // 收集相同系数的球号
            while (currentIndex < sortedByTop100.size() && 
                   sortedByTop100.get(currentIndex).getValue().equals(currentCoefficient)) {
                sameTop100CoefficientBalls.add(sortedByTop100.get(currentIndex).getKey());
                currentIndex++;
            }
            
            int needFromThisGroup = Math.min(selectCount - result.size(), sameTop100CoefficientBalls.size());
            
            if (sameTop100CoefficientBalls.size() == 1 || needFromThisGroup == sameTop100CoefficientBalls.size()) {
                // 只有一个球或者需要全部选择
                for (int i = 0; i < needFromThisGroup; i++) {
                    result.add(sameTop100CoefficientBalls.get(i));
                }
            } else {
                // 需要进一步筛选，使用dlt_backend_history_top表
                List<Integer> selectedFromTop = selectFromBackendHistoryTop(sameTop100CoefficientBalls, needFromThisGroup);
                result.addAll(selectedFromTop);
            }
        }
        
        return result;
    }
    
    /**
     * 从dlt_backend_history_top表中选择指定数量的球号
     */
    private List<Integer> selectFromBackendHistoryTop(List<Integer> candidateBalls, int selectCount) {
        if (CollectionUtils.isEmpty(candidateBalls) || selectCount <= 0) {
            return new ArrayList<>();
        }
        
        if (selectCount >= candidateBalls.size()) {
            return new ArrayList<>(candidateBalls);
        }
        
        // 获取在dlt_backend_history_top表中的系数
        Map<Integer, Double> topCoefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            DltBackendHistoryTop record = dltBackendHistoryTopMapper.selectOne(
                new LambdaQueryWrapper<DltBackendHistoryTop>()
                    .eq(DltBackendHistoryTop::getBallNumber, ball));
            if (record != null) {
                topCoefficients.put(ball, record.getActiveCoefficient());
            } else {
                topCoefficients.put(ball, 0.0);
            }
        }
        
        // 按系数降序排序，选择前selectCount个
        List<Map.Entry<Integer, Double>> sortedByTop = topCoefficients.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < Math.min(selectCount, sortedByTop.size()); i++) {
            result.add(sortedByTop.get(i).getKey());
        }
        
        // 如果仍然不够，按原始顺序补充
        while (result.size() < selectCount && result.size() < candidateBalls.size()) {
            for (Integer ball : candidateBalls) {
                if (!result.contains(ball) && result.size() < selectCount) {
                    result.add(ball);
                }
            }
        }
        
        return result;
    }

    /**
     * 处理边界冲突（毛边）
     */
    private Integer handleBoundaryConflicts(List<Integer> candidateBalls) {
        if (CollectionUtils.isEmpty(candidateBalls)) {
            return null;
        }
        
        if (candidateBalls.size() == 1) {
            return candidateBalls.get(0);
        }
        
        // 1. 先从dlt_backend_history_top_100比较
        Map<Integer, Double> top100Coefficients = new HashMap<>();
        for (Integer ball : candidateBalls) {
            DltBackendHistoryTop100 record = dltBackendHistoryTop100Mapper.selectOne(
                new LambdaQueryWrapper<DltBackendHistoryTop100>()
                    .eq(DltBackendHistoryTop100::getBallNumber, ball));
            if (record != null) {
                                 top100Coefficients.put(ball, record.getActiveCoefficient());
            } else {
                top100Coefficients.put(ball, 0.0);
            }
        }
        
        // 找出系数最大的球
        Optional<Map.Entry<Integer, Double>> maxTop100Entry = top100Coefficients.entrySet().stream()
                .max(Map.Entry.comparingByValue());
        
        if (maxTop100Entry.isPresent()) {
            Double maxCoefficient = maxTop100Entry.get().getValue();
            List<Integer> maxCoefficientBalls = top100Coefficients.entrySet().stream()
                    .filter(e -> e.getValue().equals(maxCoefficient))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            
            if (maxCoefficientBalls.size() == 1) {
                return maxCoefficientBalls.get(0);
            }
            
            // 2. 如果仍有多个球系数相同，从dlt_backend_history_top比较
            Map<Integer, Double> topCoefficients = new HashMap<>();
            for (Integer ball : maxCoefficientBalls) {
                DltBackendHistoryTop record = dltBackendHistoryTopMapper.selectOne(
                    new LambdaQueryWrapper<DltBackendHistoryTop>()
                        .eq(DltBackendHistoryTop::getBallNumber, ball));
                if (record != null) {
                                         topCoefficients.put(ball, record.getActiveCoefficient());
                } else {
                    topCoefficients.put(ball, 0.0);
                }
            }
            
            Optional<Map.Entry<Integer, Double>> maxTopEntry = topCoefficients.entrySet().stream()
                    .max(Map.Entry.comparingByValue());
            
            if (maxTopEntry.isPresent()) {
                Double maxTopCoefficient = maxTopEntry.get().getValue();
                List<Integer> maxTopCoefficientBalls = topCoefficients.entrySet().stream()
                        .filter(e -> e.getValue().equals(maxTopCoefficient))
                        .map(Map.Entry::getKey)
                        .collect(Collectors.toList());
                
                if (maxTopCoefficientBalls.size() == 1) {
                    return maxTopCoefficientBalls.get(0);
                }
            }
        }
        
        // 3. 如果仍无法区分，默认选择第一位
        return candidateBalls.get(0);
    }
    
    /**
     * 从所有候选球中筛选最终的4个球（带过程）
     * @param allCandidateBalls 所有候选球
     * @param d6CoefficientMap D6表中的系数信息
     * @return 最终选出的4个球和筛选过程
     */
    private BackBallPredictionResult selectFinal4BallsWithProcess(List<Integer> allCandidateBalls, Map<Integer, List<BallWithCoefficient>> d6CoefficientMap) {
        // 统计球号出现次数
        Map<Integer, Integer> ballFrequencyMap = new HashMap<>();
        for (Integer ball : allCandidateBalls) {
            ballFrequencyMap.put(ball, ballFrequencyMap.getOrDefault(ball, 0) + 1);
        }
        
        // 按频率分组
        Map<Integer, List<Integer>> frequencyGroups = new TreeMap<>((f1, f2) -> f2.compareTo(f1)); // 降序
        for (Map.Entry<Integer, Integer> entry : ballFrequencyMap.entrySet()) {
            frequencyGroups.computeIfAbsent(entry.getValue(), k -> new ArrayList<>()).add(entry.getKey());
        }
        
        StringBuilder processBuilder = new StringBuilder();
        List<Integer> resultBalls = new ArrayList<>();
        List<Integer> directSelected = new ArrayList<>();
        List<Integer> needFurtherSelection = new ArrayList<>();
        boolean hasSecondarySelection = false;
        String selectionSteps = "";
        String detailedCoefficientInfo = "";
        
        // 首先确定实际参与筛选的最低频率
        int currentSelected = 0;
        int minSelectedFrequency = 0;
        for (Map.Entry<Integer, List<Integer>> frequencyGroup : frequencyGroups.entrySet()) {
            int frequency = frequencyGroup.getKey();
            int ballsInGroup = frequencyGroup.getValue().size();
            
            if (currentSelected + ballsInGroup <= 4) {
                // 这个频率组的球全部入选
                currentSelected += ballsInGroup;
                minSelectedFrequency = frequency;
            } else {
                // 这个频率组只有部分球入选
                minSelectedFrequency = frequency;
                break;
            }
        }
        
        // 生成频率分布描述
        List<String> frequencyDescriptions = new ArrayList<>();
        for (Map.Entry<Integer, List<Integer>> frequencyGroup : frequencyGroups.entrySet()) {
            int frequency = frequencyGroup.getKey();
            if (frequency >= minSelectedFrequency) {
                List<Integer> ballsInGroup = new ArrayList<>(frequencyGroup.getValue());
                Collections.sort(ballsInGroup);
                String ballsStr = ballsInGroup.stream().map(String::valueOf).collect(Collectors.joining(", "));
                frequencyDescriptions.add(ballsStr + "（出现" + frequency + "次）");
            }
        }
        processBuilder.append("参与筛选的候选球号按频率分布为").append(String.join("，", frequencyDescriptions)).append("；");
        
        // 按频率从高到低处理每个频率组
        for (Map.Entry<Integer, List<Integer>> frequencyGroup : frequencyGroups.entrySet()) {
            if (resultBalls.size() >= 4) {
                break;
            }
            
            List<Integer> ballsInGroup = frequencyGroup.getValue();
            int needCount = Math.min(4 - resultBalls.size(), ballsInGroup.size());
            
            if (ballsInGroup.size() <= needCount) {
                // 如果这个频率组的球数量 <= 需要的数量，全部加入
                resultBalls.addAll(ballsInGroup);
                directSelected.addAll(ballsInGroup);
            } else {
                // 需要从这个频率组中选择部分球号，使用D6系数筛选
                List<Integer> selectedFromGroup = selectBallsByD6Coefficient(ballsInGroup, d6CoefficientMap, needCount);
                resultBalls.addAll(selectedFromGroup);
                needFurtherSelection.addAll(ballsInGroup);
                hasSecondarySelection = true;
                selectionSteps = "通过频率筛选确定部分球号，通过D6系数和筛选确定剩余球号，无需进行百期排位、历史排位";
                
                // 生成系数详情信息
                Map<Integer, Double> ballCoefficientSum = new HashMap<>();
                for (Integer ball : ballsInGroup) {
                    List<BallWithCoefficient> coefficients = d6CoefficientMap.getOrDefault(ball, new ArrayList<>());
                    double sum = coefficients.stream().mapToDouble(BallWithCoefficient::getCoefficient).sum();
                    ballCoefficientSum.put(ball, sum);
                }
                
                List<String> coefficientDetails = new ArrayList<>();
                for (Map.Entry<Integer, Double> entry : ballCoefficientSum.entrySet()) {
                    coefficientDetails.add(entry.getKey() + "（系数和" + String.format("%.2f", entry.getValue()) + "）");
                }
                Collections.sort(coefficientDetails);
                detailedCoefficientInfo = "D6系数和详情：" + String.join("，", coefficientDetails);
                
                break; // 只处理需要筛选的第一组
            }
        }
        
        // 生成筛选过程说明
        if (hasSecondarySelection) {
            processBuilder.append("无法直接筛选出前4个，其中");
            Collections.sort(directSelected);
            String directSelectedStr = directSelected.stream().map(String::valueOf).collect(Collectors.joining(", "));
            processBuilder.append(directSelectedStr).append("直接入选，");
            
            Collections.sort(needFurtherSelection);
            String needFurtherStr = needFurtherSelection.stream().map(String::valueOf).collect(Collectors.joining(", "));
            processBuilder.append(needFurtherStr).append("需要进行二次筛选，");
            
            List<Integer> finalSelected = new ArrayList<>(resultBalls);
            finalSelected.removeAll(directSelected);
            Collections.sort(finalSelected);
            String finalSelectedStr = finalSelected.stream().map(String::valueOf).collect(Collectors.joining(", "));
            processBuilder.append("最终筛选出").append(finalSelectedStr).append("，");
            
            String allResultStr = resultBalls.stream().map(String::valueOf).collect(Collectors.joining(", "));
            processBuilder.append("组成前4个球号：").append(allResultStr).append("。");
            
            processBuilder.append("筛选步骤：").append(selectionSteps).append("。");
            if (!detailedCoefficientInfo.isEmpty()) {
                processBuilder.append(" ").append(detailedCoefficientInfo).append("。");
            }
        } else {
            String allResultStr = resultBalls.stream().map(String::valueOf).collect(Collectors.joining(", "));
            processBuilder.append("直接筛选出前4个球号：").append(allResultStr).append("。");
        }
        
        // 无论是否有二次筛选，都要显示筛选步骤
        if (!hasSecondarySelection || selectionSteps.isEmpty()) {
            processBuilder.append("筛选步骤：通过频率筛选确定所有球号，无需进行D6系数筛选、百期排位、历史排位。");
        }
        
        return new BackBallPredictionResult(resultBalls, processBuilder.toString());
    }
    
    /**
     * 从所有候选球中筛选最终的4个球
     * @param allCandidateBalls 所有候选球
     * @param d6CoefficientMap D6表中的系数信息
     * @return 最终选出的4个球
     */
    private List<Integer> selectFinal4Balls(List<Integer> allCandidateBalls, Map<Integer, List<BallWithCoefficient>> d6CoefficientMap) {
        // 统计球号出现次数
        Map<Integer, Integer> ballFrequencyMap = new HashMap<>();
        for (Integer ball : allCandidateBalls) {
            ballFrequencyMap.put(ball, ballFrequencyMap.getOrDefault(ball, 0) + 1);
        }
        
        // 按出现频率分组
        Map<Integer, List<Integer>> frequencyGroups = new TreeMap<>((f1, f2) -> f2.compareTo(f1)); // 频率从高到低
        for (Map.Entry<Integer, Integer> entry : ballFrequencyMap.entrySet()) {
            frequencyGroups.computeIfAbsent(entry.getValue(), k -> new ArrayList<>()).add(entry.getKey());
        }
        
        List<Integer> resultBalls = new ArrayList<>();
        
        // 按频率组从高到低处理
        for (Map.Entry<Integer, List<Integer>> frequencyGroup : frequencyGroups.entrySet()) {
            if (resultBalls.size() >= 4) {
                break;
            }
            
            List<Integer> ballsInGroup = frequencyGroup.getValue();
            int needCount = Math.min(4 - resultBalls.size(), ballsInGroup.size());
            
            if (ballsInGroup.size() == 1) {
                // 只有一个球号，直接加入
                resultBalls.add(ballsInGroup.get(0));
            } else if (needCount == ballsInGroup.size()) {
                // 需要全部球号，全部加入
                resultBalls.addAll(ballsInGroup);
            } else {
                // 需要从多个球号中选择部分，按D6系数排序
                List<Integer> selectedBalls = selectBallsByD6Coefficient(ballsInGroup, d6CoefficientMap, needCount);
                resultBalls.addAll(selectedBalls);
            }
        }
        
        return resultBalls;
    }
    
    /**
     * 根据D6系数选择指定数量的球号
     */
    private List<Integer> selectBallsByD6Coefficient(List<Integer> candidateBalls, Map<Integer, List<BallWithCoefficient>> d6CoefficientMap, int needCount) {
        // 计算每个球号的D6系数总和
        Map<Integer, Double> ballCoefficientSum = new HashMap<>();
        for (Integer ball : candidateBalls) {
            List<BallWithCoefficient> coefficients = d6CoefficientMap.getOrDefault(ball, new ArrayList<>());
            double sum = coefficients.stream()
                    .mapToDouble(BallWithCoefficient::getCoefficient)
                    .sum();
            ballCoefficientSum.put(ball, sum);
        }
        
        // 按系数从大到小排序
        List<Map.Entry<Integer, Double>> sortedByCoefficient = ballCoefficientSum.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < needCount && index < sortedByCoefficient.size()) {
            double currentCoefficient = sortedByCoefficient.get(index).getValue();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < sortedByCoefficient.size() && 
                   sortedByCoefficient.get(index).getValue().equals(currentCoefficient)) {
                sameCoefficientBalls.add(sortedByCoefficient.get(index).getKey());
                index++;
            }
            
            // 计算还需要多少个球
            int currentNeedCount = Math.min(needCount - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(sameCoefficientBalls.get(0));
                addedCount++;
            } else if (currentNeedCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                result.addAll(sameCoefficientBalls);
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，按百期排行筛选
                List<Integer> selectedBalls = selectBallsByBackendHistoryRanking(sameCoefficientBalls, currentNeedCount);
                result.addAll(selectedBalls);
                addedCount += selectedBalls.size();
            }
        }
        
        return result;
    }
    
    /**
     * 根据后区历史排行选择指定数量的球号
     */
    private List<Integer> selectBallsByBackendHistoryRanking(List<Integer> candidateBalls, int needCount) {
        // 先尝试按百期排行筛选
        Map<Integer, Double> top100Rankings = getBackendHistoryTop100Rankings(candidateBalls);
        
        List<Map.Entry<Integer, Double>> sortedByTop100 = top100Rankings.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toList());
        
        List<Integer> result = new ArrayList<>();
        int index = 0;
        int addedCount = 0;
        
        while (addedCount < needCount && index < sortedByTop100.size()) {
            double currentCoefficient = sortedByTop100.get(index).getValue();
            List<Integer> sameCoefficientBalls = new ArrayList<>();
            
            // 收集所有相同系数的球号
            while (index < sortedByTop100.size() && 
                   sortedByTop100.get(index).getValue().equals(currentCoefficient)) {
                sameCoefficientBalls.add(sortedByTop100.get(index).getKey());
                index++;
            }
            
            // 计算还需要多少个球
            int currentNeedCount = Math.min(needCount - addedCount, sameCoefficientBalls.size());
            
            if (sameCoefficientBalls.size() == 1) {
                // 只有一个球号，直接加入
                result.add(sameCoefficientBalls.get(0));
                addedCount++;
            } else if (currentNeedCount == sameCoefficientBalls.size()) {
                // 需要选择的数量等于可用数量，全部加入
                result.addAll(sameCoefficientBalls);
                addedCount += sameCoefficientBalls.size();
            } else {
                // 需要从多个相同系数的球号中选择部分，按历史排行筛选
                Map<Integer, Double> topRankings = getBackendHistoryTopRankings(sameCoefficientBalls);
                
                List<Map.Entry<Integer, Double>> sortedByTop = topRankings.entrySet().stream()
                        .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                        .collect(Collectors.toList());
                
                for (int i = 0; i < Math.min(currentNeedCount, sortedByTop.size()); i++) {
                    result.add(sortedByTop.get(i).getKey());
                    addedCount++;
                }
            }
        }
        
        return result;
    }

    /**
     * 获取球号在后区百期排行表中的系数
     */
    private Map<Integer, Double> getBackendHistoryTop100Rankings(List<Integer> balls) {
        Map<Integer, Double> result = new HashMap<>();
        for (Integer ball : balls) {
            DltBackendHistoryTop100 record = dltBackendHistoryTop100Mapper.selectOne(
                new LambdaQueryWrapper<DltBackendHistoryTop100>()
                    .eq(DltBackendHistoryTop100::getBallNumber, ball));
                         result.put(ball, record != null ? record.getActiveCoefficient() : 0.0);
        }
        return result;
    }

    /**
     * 获取球号在后区历史排行表中的系数
     */
    private Map<Integer, Double> getBackendHistoryTopRankings(List<Integer> balls) {
        Map<Integer, Double> result = new HashMap<>();
        for (Integer ball : balls) {
            DltBackendHistoryTop record = dltBackendHistoryTopMapper.selectOne(
                new LambdaQueryWrapper<DltBackendHistoryTop>()
                    .eq(DltBackendHistoryTop::getBallNumber, ball));
                         result.put(ball, record != null ? record.getActiveCoefficient() : 0.0);
        }
        return result;
    }

    /**
     * 验证输入参数
     */
    private void validateInputParams(String level, List<Integer> nextFrontBalls, List<Integer> previousFrontBalls, 
                                  List<Integer> previousBackBalls, List<Integer> nextBackBalls) {
        if (!"high".equalsIgnoreCase(level) && !"middle".equalsIgnoreCase(level) && !"low".equalsIgnoreCase(level)) {
            throw new IllegalArgumentException("位置级别必须是high/middle/low之一");
        }
        
        if (CollectionUtils.isEmpty(nextFrontBalls) || nextFrontBalls.size() != 5) {
            throw new IllegalArgumentException("下期前区号码必须为5个");
        }
        
        if (CollectionUtils.isEmpty(previousFrontBalls) || previousFrontBalls.size() != 5) {
            throw new IllegalArgumentException("上期前区号码必须为5个");
        }
        
        if (CollectionUtils.isEmpty(previousBackBalls) || previousBackBalls.size() != 2) {
            throw new IllegalArgumentException("上期后区号码必须为2个");
        }
        
        if (CollectionUtils.isEmpty(nextBackBalls) || nextBackBalls.size() != 2) {
            throw new IllegalArgumentException("下期后区号码必须为2个");
        }
        
        for (Integer frontBall : nextFrontBalls) {
            if (frontBall < 1 || frontBall > 35) {
                throw new IllegalArgumentException("前区号码范围应为1-35");
            }
        }
        
        for (Integer frontBall : previousFrontBalls) {
            if (frontBall < 1 || frontBall > 35) {
                throw new IllegalArgumentException("前区号码范围应为1-35");
            }
        }
        
        for (Integer backBall : previousBackBalls) {
            if (backBall < 1 || backBall > 12) {
                throw new IllegalArgumentException("后区号码范围应为1-12");
            }
        }
        
        for (Integer backBall : nextBackBalls) {
            if (backBall < 1 || backBall > 12) {
                throw new IllegalArgumentException("后区号码范围应为1-12");
            }
        }
    }
}